//
//  MTCityViewController.m
//  美团HD
//
//  Created by apple on 14/11/23.
//  Copyright (c) 2014年 heima. All rights reserved.
//

#import "MTCityViewController.h"
#import "UIBarButtonItem+Extension.h"
#import "MTCityGroup.h"
#import "MJExtension.h"
//#import "MTConst.h"
#import "UIView+AutoLayout.h"
#import "MTCitySearchResultViewController.h"
#import "UIImage+Extension.h"
#import "LECity.h"
#import "NSObject+XML.h"
#import "LEProvinceXML.h"

const int MTCoverTag = 999;

@interface MTCityViewController () <UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>
//@property (nonatomic, strong) NSArray *cityGroups;
@property(nonatomic, strong) NSArray *citys;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *cover;
- (IBAction)coverClick;
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (nonatomic, weak) MTCitySearchResultViewController *citySearchResult;

@property(nonatomic, copy) LESelectedCity selectedCityBlock;
@end

@implementation MTCityViewController

- (MTCitySearchResultViewController *)citySearchResult {
    if (!_citySearchResult) {
        MTCitySearchResultViewController *citySearchResult = [[MTCitySearchResultViewController alloc] init];
        [self addChildViewController:citySearchResult];
        self.citySearchResult = citySearchResult;
        CYWeakObject(weakself, self);
        [citySearchResult selectedCity:^(NSString *city) {
            weakself.selectedCityBlock(city);
            [weakself dismissViewControllerAnimated:YES completion:^{
                weakself.selectedCityBlock = nil;
            }];
        }];
        
        [self.view addSubview:self.citySearchResult.view];
        [self.citySearchResult didMoveToParentViewController:self];
        [self.citySearchResult.view autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero excludingEdge:ALEdgeTop];
        [self.citySearchResult.view autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.searchBar withOffset:15];
    }
    return _citySearchResult;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 基本设置
    self.title = @"切换城市";
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(close) image:@"btn_navigation_close_hl" highImage:@"btn_navigation_close_hl"];
    self.tableView.sectionIndexColor = [UIColor blackColor];
    
    // 加载城市数据
//    self.cityGroups = [MTCityGroup objectArrayWithFilename:@"cityGroups.plist"];
//    self.citys = [LECity objectArrayWithFilename:@"city.plist"];
//    self.citys = [self.citys subarrayWithRange:NSMakeRange(1, self.citys.count - 1)];
    LEProvinceXML *xml = [LEProvinceXML objectWithXMLFilename:@"area.xml"];
    self.citys = xml.province;
    
    self.searchBar.tintColor = CYColor(32, 191, 179, 1);
    [self.searchBar setBackgroundImage:[UIImage resizedImageWithName:@"bg_login_textfield"]];
    [self seupItem];
}

- (void)seupItem {
    UIBarButtonItem *cancel = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
    self.navigationItem.rightBarButtonItem = cancel;
}

- (void)close {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 搜索框代理方法
/**
 *  键盘弹出:搜索框开始编辑文字
 */
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    // 1.隐藏导航栏
//    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    // 2.修改搜索框的背景图片
    [searchBar setBackgroundImage:[UIImage resizedImageWithName:@"bg_login_textfield_hl"]];
    
    // 3.显示搜索框右边的取消按钮
    [searchBar setShowsCancelButton:YES animated:YES];
    
    // 4.显示遮盖
    [UIView animateWithDuration:0.5 animations:^{
        self.cover.alpha = 0.5;
    }];
}

/**
 *  键盘退下:搜索框结束编辑文字
 */
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    // 1.显示导航栏
//    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    // 2.修改搜索框的背景图片
    [searchBar setBackgroundImage:[UIImage resizedImageWithName:@"bg_login_textfield"]];
    
    // 3.隐藏搜索框右边的取消按钮
    [searchBar setShowsCancelButton:NO animated:YES];
    
    // 4.隐藏遮盖
    [UIView animateWithDuration:0.5 animations:^{
        self.cover.alpha = 0.0;
    }];
    
    // 5.移除搜索结果
    self.citySearchResult.view.hidden = YES;
    searchBar.text = nil;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
}

/**
 *  搜索框里面的文字变化的时候调用
 */
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if (searchText.length) {
        self.citySearchResult.view.hidden = NO;
        self.citySearchResult.searchText = searchText;
    } else {
        self.citySearchResult.view.hidden = YES;
    }
}

/**
 *  点击遮盖
 */
- (IBAction)coverClick {
    [self.searchBar resignFirstResponder];
}

#pragma mark - 数据源方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    return self.cityGroups.count;
    return self.citys.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    MTCityGroup *group = self.cityGroups[section];
//    return group.cities.count;
//    LECity *city = self.citys[section];
    LEAreaXML *area = self.citys[section];
    return area.city.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"city";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    
//    MTCityGroup *group = self.cityGroups[indexPath.section];
//    cell.textLabel.text = group.cities[indexPath.row];
//    LECity *city = self.citys[indexPath.section];
//    cell.textLabel.text = city.cities[indexPath.row];
    LEAreaXML *area = self.citys[indexPath.section];
    LECountryXML *country = area.city[indexPath.row];
    cell.textLabel.text = country._name;
    
    return cell;
}

#pragma mark - 代理方法
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
//    MTCityGroup *group = self.cityGroups[section];
//    LECity *group = self.citys[section];
//    return group.title;
//    return group.state;
    LEAreaXML *area = self.citys[section];
    return area._name;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
//    return [self.cityGroups valueForKeyPath:@"title"];
    return [self.citys valueForKeyPath:@"_name"];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    MTCityGroup *group = self.cityGroups[indexPath.section];
//    LECity *group = self.citys[indexPath.section];
    LEAreaXML *area = self.citys[indexPath.section];
    LECountryXML *country = area.city[indexPath.row];
    NSLog(@"country = %@",country);
    
    // 发出通知
    [CYNotificationCenter postNotificationName:MTCityDidChangeNotification object:nil userInfo:@{MTSelectCityName : country._name}];
    self.selectedCityBlock(country._name);
    CYWeakObject(weakself, self);
    [self dismissViewControllerAnimated:YES completion:^{
        weakself.selectedCityBlock = nil;
    }];
}

- (void)selectedCity:(LESelectedCity)selectedCity {
    self.selectedCityBlock = [selectedCity copy];
}
@end
